<template>
  <div class="services">
    <div class="services_search">
      <el-input
        v-model="input_search_value"
        style="max-width: 600px; margin-left: 10px"
        placeholder="请输入搜索内容"
        class="input-with-select"
      >
        <template #prepend>
          <el-select
            v-model="select_search_value"
            placeholder="选择搜索选项"
            style="width: 115px"
          >
            <el-option
              v-for="item in search_value"
              :label="item.label"
              :value="item.prop"
              :key="item.prop"
            />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" />
        </template>
      </el-input>
    </div>
    <div class="services_func">
      <el-button
        style="margin-left: 10px"
        type="primary"
        @click="addData"
        v-if="isSWSJFW"
        >
        新增
      </el-button
      >
<!--      <el-button @click="editData">编辑</el-button>-->
      <el-button @click="deleteDataById" v-if="isSWSJFW">删除</el-button>
      <el-button @click="dataRequest">申请</el-button>
    </div>
    <div class="services_list">
      <el-table
        :data="w3d_services_data_filter"
        style="width: 99%"
        @selection-change="handleSelectionChange"
        highlight-current-row
      >
        <el-table-column type="selection" />
        <el-table-column label="数据名称">
          <template #default="scope">
            <span>{{ scope.row.other_name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="三维数据类型">
          <template #default="scope">
            <span>{{ scope.row.data_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称">
          <template #default="scope">
            <span>{{ scope.row.data_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行政区划">
          <template #default="scope">
            <span>{{ scope.row.administrative_region }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批数据类型">
          <template #default="scope">
            <span>{{ scope.row.approval_data_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据发布时间">
          <template #default="scope">
            <span>{{ scope.row.publish_time }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="editRow(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="services_page">
      <div style="margin-left: 10px">
        <el-pagination
          v-model:current-page="tableDataPagination.page_no"
          v-model:page-size="tableDataPagination.page_size"
          :page-sizes="[10, 20, 30, 40, 50]"
          v-model:total="tableDataPaginationTotal"
        />
      </div>
    </div>
  </div>
  <div v-if="is_data_requests" class="data_request">
    <data-requests
      :data_request="selected_w3d_services_data"
      :data_request_user="data_request_user"
      @close_card="closeDataRequest"
    />
  </div>
    <div v-if="is_show_add_form" class="data_edit_add">
    <data-edit-add
      :add_w3d_services_data="add_w3d_services_data"
      :is_edit_data="is_edit_data"
      :forbid_administrative_region="forbid_administrative_region"
      @close_card="closeDataEditAdd"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, watch ,computed} from "vue";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { throttle } from "lodash";
import {
  getW3dServiceInfoPage,
  deleteW3dServiceInfoById,
  getW3dServiceInfoCatalogue,
  getW3dServiceInfoById
} from "@/api/W3dServiceApi";
import { getLoginUserAndMenu, getUserInfoByID } from "@/api/userApi";
import DataRequests from "./components/DataRequests.vue";
import dataEditAdd from "./components/dataEditAdd.vue";

const isSWSJFW = ref(true)

// 加载数据
const w3d_services_data = ref([]);
const selected_w3d_services_data = ref([]);

// 搜索
const search_value = ref([
  {
    label: "数据名称",
    prop: "data_name",
  },
  {
    label: "行政区划",
    prop: "administrative_region",
  },
  {
    label: "审批数据类型",
    prop: "approval_data_type",
  },
  {
    label: "三维数据类型",
    prop: "data_type",
  },
]);

// 为了保证街道内不能重复添加白膜数据
const forbid_administrative_region = ref([])

// 搜索条件
const select_search_value = ref("data_name");
const input_search_value = ref("");

const data_request_user = ref({
  applicant: "sa",
  department: "sql",
  tel: "12345678901",
});

// 页面分页
const tableDataPagination = ref({
  page_no: 1,
  page_size: 10,
});

const tableDataPaginationTotal = ref(8);

// 根据搜索条件过滤数据
const w3d_services_data_filter = computed(() => {
  const tempData =  w3d_services_data.value.filter((item) => {
    switch (select_search_value.value) {
      case "data_name":
        return item.data_name.includes(input_search_value.value);
      case "administrative_region":
        return item.administrative_region.includes(input_search_value.value);
      case "approval_data_type":
        return item.approval_data_type.includes(input_search_value.value);
      case "data_type":
        return item.data_type.includes(input_search_value.value);
      default:
        return true;
    }
  });
  tableDataPaginationTotal.value = tempData.length;
  // 按照发布时间排序
  tempData.sort((a, b) => new Date(b.publish_time) - new Date(a.publish_time));

  // 根据分页条件过滤数据
  return tempData.slice(
    (tableDataPagination.value.page_no - 1) * tableDataPagination.value.page_size,
    tableDataPagination.value.page_no * tableDataPagination.value.page_size
  );
});


// 获取用户信息及token
const getUserInfo = () => {
  getLoginUserAndMenu().then(res => {
    if(res.code === 200) {
      getUserInfoByID(res.data.user.userId).then(userData => {
        data_request_user.value = {
          applicant: userData.fullName,
          department: userData.deptName,
          tel: userData.mobile,
        }
      });
    }
  });
};

function getTokenFromUrl() {
  const params = new URLSearchParams(window.location.search);
  const token = params.get('authorization');
  if(token) {
    localStorage.setItem('authorization', token);
    const url = new URL(window.location.href);
    url.searchParams.delete('authorization');
    window.history.replaceState({}, '', url);
  }
}

const update_w3d_services_data = () => {
  w3d_services_data.value = []
  forbid_administrative_region.value = []
  getW3dServiceInfoCatalogue().then(res => {
    if(res.code === 0) {
      for(let i=0;i<res.data.length;i++) {
        const dataRoot = res.data[i];
        if(dataRoot.name==="白模"){
          processBaiMoTree(dataRoot.children);
        }
        if(dataRoot.name==="倾斜"){
          processQinXieTree(dataRoot.children);
        }
      }
    } else {
      ElMessage.error("网络错误！");
    }
  });
};

// 处理倾斜模型数据
const processQinXieTree = (treeList) => {
  for(let i = 0;i<treeList.length;i++){
    const administrative_region_level_tree = treeList[i];
    if( !administrative_region_level_tree.children || administrative_region_level_tree.children.length === 0) {
      continue;
    }
    for (let j=0;j<administrative_region_level_tree.children.length;j++){
      const project_level_tree = administrative_region_level_tree.children[j];
      if(!project_level_tree.children || project_level_tree.children.length === 0) {
        continue;
      }
      const project_name = project_level_tree.name
      for(let k=0;k<project_level_tree.children.length;k++){
        const data_level_tree = project_level_tree.children[k];
        const dataId = data_level_tree.id;

        getW3dServiceInfoById(dataId).then(res => {
          if(res.code === 0) {
            const data = {
              data_id : dataId,
              other_name: res.data.other_name ? res.data.other_name:"-", // 等待修改
              data_name: project_name,  // 作为项目名称
              data_type: res.data.data_type, //
              approval_data_type: res.data.approval_data_type,
              publish_time: res.data.publish_time,
              administrative_region: res.data.administrative_region,
              service_url : res.data.service_url,
              data_storage_addr : res.data?.data_storage_addr,
            }
            w3d_services_data.value.push(data)
          }
        })
      }
    }
  }
}


// 处理白膜数据
const processBaiMoTree = (treeList) => {
  for(let i=  0;i<treeList.length;i++) {
    const administrative_region = treeList[i].name
    if(treeList[i].children && treeList[i].children.length > 0) {
      // 项目级别了,对于一个行政区下白膜只有一个项目
      const firstProject = treeList[i].children[0]
      // 数据界别，对于一个项目下只有一个白膜
      if(firstProject.children && firstProject.children.length>0){
        const firstData = firstProject.children[0]
        const dataId = firstData.id
        getW3dServiceInfoById(dataId).then(res => {
          forbid_administrative_region.value.push(administrative_region)
          if(res.code === 0) {
            const data = {
              data_id : dataId,
              other_name: res.data.other_name ? res.data.other_name:"-", // 等待修改
              data_name: "-",
              data_type: res.data.data_type,
              approval_data_type: res.data.approval_data_type,
              publish_time: res.data.publish_time,
              administrative_region: administrative_region,
              service_url : res.data.service_url,
              data_storage_addr : res.data?.data_storage_addr,
            }
            w3d_services_data.value.push(data)
          }
        })
      }
    }
  }
};


// 增删改查
const is_show_add_form = ref(false);
const is_edit_data = ref(false);
const add_w3d_services_data = ref({});

const closeDataEditAdd = (val) => {
  is_show_add_form.value = val;
  is_edit_data.value = val;
  update_w3d_services_data();
};


const addData = () => {
  is_show_add_form.value = true;
  add_w3d_services_data.value = {};
};

const editRow = (row) => {
  is_edit_data.value = true;
  is_show_add_form.value = true;
  add_w3d_services_data.value = row;
};

const deleteDataById = () => {
  if (selected_w3d_services_data.value.length === 0) {
    ElMessage.warning("请选择要删除的数据！");
    return;
  }
  Promise.all(
    selected_w3d_services_data.value.map((item) => {
      return deleteW3dServiceInfoById(item.data_id);
    })
  ).then((res) => {
    res.forEach((item) => {
      if (item.code === 0) {
        ElMessage({
          message: "删除成功！",
          type: "success",
        });
      } else {
        ElMessage({
          message: item.msg,
          type: "error",
        });
      }
    });
    update_w3d_services_data()
  });
};

//
const is_data_requests = ref(false);
const dataRequest = () => {
  if (selected_w3d_services_data.value.length === 0) {
    ElMessage.warning("请先选择申请数据！");
    return;
  }
  is_data_requests.value = true;
};

const closeDataRequest = (val) => {
  is_data_requests.value = val;
};

const handleSelectionChange = (val) => {
  selected_w3d_services_data.value = val;
};


onMounted(() => {
  update_w3d_services_data()
  getTokenFromUrl();
  getUserInfo();

  // 获取当前的页面地址
  const currentPath = window.location.pathname;
  isSWSJFW.value = !currentPath.includes("swszsq");
});
</script>

<style scoped>
.services {
  display: flex;
  height: 100vh;
  overflow: hidden;
  flex-direction: column;
  justify-content: center;
}

.services_search {
  display: flex;
  flex: 0.5;
  align-items: center;
}

.services_func {
  display: flex;
  flex: 0.5;
  align-items: center;
}

.services_list {
  display: flex;
  flex: 8;
  overflow: auto;
  justify-content: center;
  align-items: flex-start;
  border-top: 1px solid var(--el-border-color);
  border-bottom: 1px solid var(--el-border-color);
}

.services_page {
  display: flex;
  flex: 0.5;
  align-items: center;
}

.data_request {
  position: absolute;
  overflow: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60vw;
  height: 80vh;
  z-index: 99;
}

.data_edit_add {
  position: absolute;
  overflow: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50vw;
  height: 60vh;
  z-index: 99;
}
</style>
